package com.jx.mlxg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jx.mlxg.common.BusinessException;
import com.jx.mlxg.common.ExceptionEnum;
import com.jx.mlxg.entity.*;
import com.jx.mlxg.mapper.*;
import com.jx.mlxg.service.ApprovalRecordService;
import com.jx.mlxg.service.MaterialRequestService;
import com.jx.mlxg.service.OrdersService;
import com.jx.mlxg.service.UsersService;
import com.jx.mlxg.utils.DateUtil;
import com.jx.mlxg.utils.PageResponse;
import com.jx.mlxg.utils.UserOrderStatisticsResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.Arrays;

/**
* @author Administrator
* @description 针对表【orders】的数据库操作Service实现
* @createDate 2025-02-25 21:15:46
*/
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private MaterialRequestServiceImpl materialRequestServiceImpl;
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailsMapper orderDetailsMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Resource
    private UsersService usersService;

    @Resource
    private ApprovalRecordService approvalRecordService;
    @Autowired
    private ShippingInfoMapper shippingInfoMapper;
    @Autowired
    private AddressesMapper addressesMapper;

    @Override
    @Transactional
    public String createOrderByRequestId(MaterialRequest materialRequest) {
        try{

            System.out.println("createOrderByRequestId");
            // 1. 根据发货申请 ID 查询发货申请信息
//        MaterialRequest materialRequest = materialRequestServiceImpl.selectByRequestId(requestId);
            System.out.println("materialRequest--->" + materialRequest);
            if (materialRequest == null) {
                log.error("【订单创建】发货申请不存在，请求materialRequest：{}"+materialRequest);
                throw new BusinessException(ExceptionEnum.MATERIAL_REQUEST_NOT_EXIST);
            }


            // 获取当前登录用户的ID（假设通过Spring Security获取）
            // 从 SecurityContextHolder 中获取当前登录用户的信息
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String openIdStr = (String) principal;
            log.info("【用户信息】获取OpenID成功：{}", openIdStr);
            Users userInfoAndOrderStatistics = usersService.findByOpenId(openIdStr);
            if (userInfoAndOrderStatistics == null) {
                log.error("【用户校验】用户信息不存在，OpenID：{}", openIdStr);
                throw new BusinessException(ExceptionEnum.USER_NOT_FOUND);
            }
            log.info("【用户校验】用户ID：{}", userInfoAndOrderStatistics.getUserId());
            // 2. 创建订单
            Orders orders = new Orders();
            // 根据用户名获取用户ID
            orders.setUserId(userInfoAndOrderStatistics.getUserId()); // 假设申请人就是用户 ID
            log.info("【订单生成】订单创建成功，订单：{}", orders);
            orders.setStatus("待支付");
            // 先对 materialRequest.getDiscountAmount() 进行判空处理
            BigDecimal discountAmount = materialRequest.getDiscountAmount();
            if (discountAmount == null) {
                discountAmount = BigDecimal.ZERO;
            }
            orders.setRealAmount(materialRequest.getTotalMoney());
            orders.setTotalAmount(materialRequest.getTotalMoney().add(discountAmount));
            orders.setDiscountAmount(materialRequest.getDiscountAmount());
            // 生成订单号（示例：当前时间戳 + 随机数）
            String orderSn = System.currentTimeMillis() + "-" + new Random().nextInt(1000);
//            orders.setAddressId(materialRequest.getAddressId());
            orders.setOrderId(String.valueOf(orderSn));
            orders.setRemark(materialRequest.getRemark());
            System.out.println("订单创建参数" + orders);
            orders.setOpenid(openIdStr);
            ordersMapper.insert(orders);

            List<Product> products = materialRequest.getProducts();
            log.info("【商品处理】开始处理{}个商品", products.size());
            for (Product product : products) {
                // 3. 创建订单明细
                OrderDetails orderDetails = new OrderDetails();
                orderDetails.setOrderId(orders.getOrderId());
                orderDetails.setProductId(product.getProductId());
                orderDetails.setQuantity(product.getQuantity());


                BigDecimal totalMoney;
                Product productById = productMapper.selectById(product.getProductId());
                if (product.getQuantity() >= productById.getMinQuantity()) { // 如果数量大于等于2，使用批量价格
                    totalMoney = productById.getBulkPrice().multiply(new BigDecimal(product.getQuantity()));
                    // 查询产品单价
                    orderDetails.setUnitPrice(productById.getBulkPrice());
                } else {
                    // 如果数量小于2，使用单桶价格（假设单桶价格是批量价格 + 40）
                    totalMoney = productById.getSinglePrice().multiply(new BigDecimal(product.getQuantity()));
                    // 查询产品单价
                    orderDetails.setUnitPrice(productById.getSinglePrice());
                }
                orderDetails.setTotalMoney(totalMoney);

                orderDetailsMapper.insert(orderDetails);
                log.info("【商品明细】处理商品ID：{}", product.getProductId());
            }
            // 4. 返回订单 ID
            return orderSn;
        }catch (BusinessException  e) {
            log.warn("【业务异常】订单创建失败，错误码：{}", e.getCode());
            throw e;
        }catch (Exception e) {
            log.error("【系统异常】订单创建错误，异常类型：{}", e.getClass().getSimpleName());
            throw new BusinessException(ExceptionEnum.ORDER_CREATION_FAILED, e.getMessage());
        }




    }

    /*@Override
    public PageResponse<Orders> listOrders(int pageNo, int pageSize) {
        try{
            IPage<Orders> page = new Page<>(pageNo, pageSize);
            // 从 SecurityContextHolder 中获取当前登录用户的信息
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String openIdStr = (String) principal;
                // 根据 userId 获取用户信息和订单统计
                Users userInfoAndOrderStatistics = usersService.findByOpenId(openIdStr);
            if (userInfoAndOrderStatistics == null) {
                throw new BusinessException(ExceptionEnum.USER_NOT_FOUND);
            }
            IPage<Orders> resultPage = null;
                    if(userInfoAndOrderStatistics.getRole().equals(0) || userInfoAndOrderStatistics.getRole().equals(1) || userInfoAndOrderStatistics.getRole().equals(2)){
                         resultPage = ordersMapper.selectPage(page, new QueryWrapper<Orders>().orderByDesc("created_at")); // 添加倒序排序);
                    }else{
                        resultPage = ordersMapper.selectPage(page, new QueryWrapper<Orders>().eq("user_id", userInfoAndOrderStatistics.getUserId()).orderByDesc("created_at"));
                    }
                // 获取订单列表
                PageResponse<Orders> response = new PageResponse<>();
                List<Orders> ordersList = resultPage.getRecords();
                // 查询每个订单的地址和产品信息
                for (Orders order : ordersList) {
                    String orderId = order.getOrderId();

                    // 查询地址信息
//                    Addresses address = ordersMapper.selectAddressByOrderId(orderId);
//                    order.setReceiver(address);
                    ShippingInfo shippingInfo = shippingInfoMapper.selectOne(new QueryWrapper<ShippingInfo>().eq("order_id", orderId));

                    Addresses addresses = addressesMapper.selectById(shippingInfo.getAddressId());
                    order.setReceiver(addresses);
                    // 查询产品信息
                    List<Product> products = ordersMapper.selectProductsByOrderId(orderId);
                    for (Product product : products) {
                        List<OrderDetails> orderDetails = orderDetailsMapper.selectList(new QueryWrapper<OrderDetails>().eq("order_id", orderId));
                        for (OrderDetails orderDetail : orderDetails) {
                            Integer productId = orderDetail.getProductId();
                            Integer quantity = orderDetail.getQuantity();
                            if (product.getProductId().equals(productId)) {
                                product.setQuantity(quantity);
                            }
                        }
                    }

                    ApprovalRecord approvalRecord = getApprovalRecordByOrderId(order.getOrderId(), userInfoAndOrderStatistics);


//                    LocalDateTime createdAt = order.getCreatedAt();
//                    long createStamp = createdAt.toEpochSecond(ZoneOffset.UTC); // 使用 UTC 时区
//                    order.setCreateStamp(createStamp);
                    // 优化后的代码：将 LocalD atetime 转换为时间戳（UTC 时区）
                    if (order.getCreatedAt() != null) {
                        try {
                            ZoneId zone = ZoneId.systemDefault();
                            ZonedDateTime zdt = order.getCreatedAt().atZone(zone);
                            order.setCreateStamp(zdt.toEpochSecond());
                        } catch (DateTimeException e) {
                            log.error("时间转换异常，订单ID："+order.getOrderId()+"错误："+ e.getMessage());
                            order.setCreateStamp(0L); // 设置默认值
                        }
                    } else {
                        log.warn("订单创建时间为空，ID：{}"+ order.getOrderId());
                        order.setCreateStamp(0L);
                    }

                    // 打印结果验证
                    System.out.println("原始时间：" + order.getCreatedAt       ());
                    System.out.println("时间戳：" + order.getCreateStamp());

                    // 验证转换是否正确
                    LocalDateTime convertBack = LocalDateTime.ofEpochSecond(order.getCreateStamp(), 0, ZoneOffset.UTC);
                    System.out.println("转换回的时间（UTC）：" + convertBack);

                    if(userInfoAndOrderStatistics.getRole() == 0 || userInfoAndOrderStatistics.getRole() == 1 || userInfoAndOrderStatistics.getRole() == 2){
                        order.setApprovalRecord(approvalRecord);
                    }else{
                        order.setApprovalRecord(null);
                    }
                    order.setProducts(products);

                }
                // 转换为自定义的分页返回对象
                response.setOrderList(ordersList);
                response.setTotal(resultPage.getTotal());
                response.setPageNo(resultPage.getCurrent());
                response.setPageSize(resultPage.getSize());
                return response;

        }catch (Exception e) {
            throw new BusinessException(ExceptionEnum.SYSTEM_ERROR, e.getMessage());
        }
    }*/
    @Override
    public PageResponse<Orders> listOrders(int pageNo, int pageSize, Map<String, Object> filterParams) {
        log.info("【订单查询】开始分页查询，页码：{}/页大小：{}", pageNo, pageSize);

        try{
            log.info("filterParams---->：{}",filterParams);
            filterParams = (Map<String, Object>) filterParams.get("filterParams");
            IPage<Orders> page = new Page<>(pageNo, pageSize);
            // 从 SecurityContextHolder 中获取当前登录用户的信息
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            log.info("principal--->{}",principal);
            String openIdStr = (String) principal;
            log.info("【用户信息】openIdStr：{}", openIdStr);
            // 根据 userId 获取用户信息和订单统计
            Users userInfoAndOrderStatistics = usersService.findByOpenId(openIdStr);
            if (userInfoAndOrderStatistics == null) {
                log.error("【用户校验】未找到用户，OpenID：{}", openIdStr);
                throw new BusinessException(ExceptionEnum.USER_NOT_FOUND);
            }
            log.info("【用户校验】用户角色：{}", userInfoAndOrderStatistics.getRole());

            // 构建基础查询条件
            QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("created_at");

            // 如果filterParams为空，则初始化为一个空Map，避免后续操作出现空指针异常
            if (filterParams == null) {
                filterParams = new HashMap<>();
            }

            // 处理时间筛选条件
            if (filterParams.containsKey("timeRange")) {
                String timeRange = (String) filterParams.get("timeRange");
                handleTimeRangeFilter(queryWrapper, timeRange, filterParams);
            }

            // 处理发货时间筛选条件
            if (filterParams.containsKey("shippedStartDate") || filterParams.containsKey("shippedEndDate")) {
                Object shippedStartDateObj = filterParams.get("shippedStartDate");
                Object shippedEndDateObj = filterParams.get("shippedEndDate");

                Timestamp shippedStartDate = null;
                Timestamp shippedEndDate = null;

                if (shippedStartDateObj != null && !shippedStartDateObj.toString().isEmpty()) {
                    try {
                        long startStamp = Long.parseLong(shippedStartDateObj.toString());
                        shippedStartDate = new Timestamp(startStamp * 1000L); // 将秒转换为毫秒
                    } catch (NumberFormatException e) {
                        log.error("发货开始时间格式错误: {}", shippedStartDateObj);
                        throw new BusinessException(ExceptionEnum.DATE_ERROR, "发货开始时间格式错误");
                    }
                }

                if (shippedEndDateObj != null && !shippedEndDateObj.toString().isEmpty()) {
                    try {
                        long endStamp = Long.parseLong(shippedEndDateObj.toString());
                        shippedEndDate = new Timestamp(endStamp * 1000L); // 将秒转换为毫秒
                    } catch (NumberFormatException e) {
                        log.error("发货结束时间格式错误: {}", shippedEndDateObj);
                        throw new BusinessException(ExceptionEnum.DATE_ERROR, "发货结束时间格式错误");
                    }
                }

                if (shippedStartDate != null) {
                    queryWrapper.ge("shipped_date", shippedStartDate);
                }
                if (shippedEndDate != null) {
                    queryWrapper.le("shipped_date", shippedEndDate);
                }
            }

            // 处理产品筛选条件
            if (filterParams.containsKey("productId")) {
                Integer productId = (Integer) filterParams.get("productId");
                List<String> orderIds = orderDetailsMapper.getOrderIdsByProductId(productId);
                if (orderIds != null && !orderIds.isEmpty()) {
                    queryWrapper.in("order_id", orderIds);
                } else {
                    // 如果没有找到相关订单，返回空结果
                    queryWrapper.eq("order_id", -1);
                }
            }

            // 处理状态筛选条件
            if (filterParams.containsKey("status")) {
                String status = (String) filterParams.get("status");
                queryWrapper.eq("status", status);
            }

            IPage<Orders> resultPage;

            // 根据用户角色确定查询范围
            if (userInfoAndOrderStatistics.getRole().equals(0) || userInfoAndOrderStatistics.getRole().equals(1) || userInfoAndOrderStatistics.getRole().equals(2)) {
                // 管理员查询所有订单（如果存在筛选条件，则查询符合条件的订单；否则查询全部）
                resultPage = ordersMapper.selectPage(page, queryWrapper);
            } else {
                // 普通用户查询自己的订单（添加user_id条件）
                queryWrapper.eq("user_id", userInfoAndOrderStatistics.getUserId());
                resultPage = ordersMapper.selectPage(page, queryWrapper);
            }

            // 获取订单列表
            PageResponse<Orders> response = new PageResponse<>();
            List<Orders> ordersList = resultPage.getRecords();

            // 查询每个订单的地址和产品信息
            for (Orders order : ordersList) {
                String orderId = order.getOrderId();

                // 查询地址信息
                ShippingInfo shippingInfo = shippingInfoMapper.selectOne(new QueryWrapper<ShippingInfo>().eq("order_id", orderId));

                Addresses addresses = addressesMapper.selectById(shippingInfo.getAddressId());
                order.setReceiver(addresses);

                // 查询产品信息
                List<Product> products = ordersMapper.selectProductsByOrderId(orderId);
                for (Product product : products) {
                    List<OrderDetails> orderDetails = orderDetailsMapper.selectList(new QueryWrapper<OrderDetails>().eq("order_id", orderId));
                    for (OrderDetails orderDetail : orderDetails) {
                        Integer productIdDetail = orderDetail.getProductId();
                        Integer quantity = orderDetail.getQuantity();
                        if (product.getProductId().equals(productIdDetail)) {
                            product.setQuantity(quantity);
                        }
                    }
                }

//                ApprovalRecord approvalRecord = getApprovalRecordByOrderId(order.getOrderId(), userInfoAndOrderStatistics);

                // 时间转换逻辑
                if (order.getCreatedAt() != null) {
                    try {
                        ZoneId zone = ZoneId.systemDefault();
                        ZonedDateTime zdt = order.getCreatedAt().atZone(zone);
                        order.setCreateStamp(zdt.toEpochSecond());
                    } catch (DateTimeException e) {
                        log.error("时间转换异常，订单ID：" + order.getOrderId() + " 错误：" + e.getMessage());
                        order.setCreateStamp(0L); // 设置默认值
                    }
                } else {
                    log.warn("订单创建时间为空，ID：" + order.getOrderId());
                    order.setCreateStamp(0L);
                }

                // 验证转换是否正确
                log.info("原始时间：{}"+order.getCreatedAt());
                System.out.println("原始时间：" + order.getCreatedAt());
                log.info("时间戳：" + order.getCreateStamp());
                System.out.println("时间戳：" + order.getCreateStamp());

                LocalDateTime convertBack = LocalDateTime.ofEpochSecond(order.getCreateStamp(), 0, ZoneOffset.UTC);
                System.out.println("转换回的时间（UTC）：" + convertBack);

//                if (userInfoAndOrderStatistics.getRole() == 0 || userInfoAndOrderStatistics.getRole() == 1 || userInfoAndOrderStatistics.getRole() == 2) {
//                    order.setApprovalRecord(approvalRecord);
//                } else {
//                    order.setApprovalRecord(null);
//                }
                order.setApprovalRecord(null);
                order.setProducts(products);
                String status = order.getStatus();
                if (status.equals("已支付") && (userInfoAndOrderStatistics.getRole() == 0 || userInfoAndOrderStatistics.getRole() == 1 || userInfoAndOrderStatistics.getRole() == 2)) {
                    order.setIsSend(true);
                } else {
                    order.setIsSend(false);
                }
            }

            // 转换为自定义的分页返回对象
            response.setOrderList(ordersList);
            response.setTotal(resultPage.getTotal());
            response.setPageNo(resultPage.getCurrent());
            response.setPageSize(resultPage.getSize());
            return response;
        } catch (BusinessException e) {
            log.warn("【业务异常】订单查询失败，错误码：{}", e.getCode());
            throw e;
        } catch (Exception e) {
            log.error("【系统异常】订单查询错误，异常类型：{}", e.getClass().getSimpleName());
            throw new BusinessException(ExceptionEnum.UNKNOWN_ERROR, e.getMessage());
        }
    }

    private void handleTimeRangeFilter(QueryWrapper<Orders> queryWrapper, String timeRange, Map<String, Object> filterParams) {
        switch (timeRange) {
            case "today":
                queryWrapper.ge("created_at", DateUtil.getTodayStart());
                queryWrapper.le("created_at", DateUtil.getTodayEnd());
                break;
            case "yesterday":
                queryWrapper.ge("created_at", DateUtil.getYesterdayStart());
                queryWrapper.le("created_at", DateUtil.getYesterdayEnd());
                break;
            case "sevenDays":
                queryWrapper.ge("created_at", DateUtil.getSevenDaysAgo());
                break;
            case "custom":
                String startDateTimeObj = filterParams.get("startTime").toString();
                String endDateTimeObj = filterParams.get("endTime").toString();

                Long startTimestamp = null;
                Long endTimestamp = null;

                // 将Long类型的时间戳转换为Timestamp
          /*  if (startDateTimeObj instanceof Long) {
                startTimestamp = (Long) startDateTimeObj;
            } else */
                if (startDateTimeObj instanceof String) {
                    try {
                        startTimestamp = Long.parseLong((String) startDateTimeObj);
                    } catch (NumberFormatException e) {
                        throw new BusinessException(ExceptionEnum.DATE_ERROR);
                    }
                }

           /* if (endDateTimeObj instanceof Long) {
                endTimestamp = (Long) endDateTimeObj;
            } else*/
                if (endDateTimeObj instanceof String) {
                    try {
                        endTimestamp = Long.parseLong((String) endDateTimeObj);
                    } catch (NumberFormatException e) {
                        throw new BusinessException(ExceptionEnum.DATE_ERROR);
                    }
                }

                Timestamp startDateTime = null;
                Timestamp endDateTime = null;

                if (startTimestamp != null && startTimestamp != 0) {
                    startDateTime = new Timestamp(startTimestamp * 1000L); // 将秒转换为毫秒
                }

                if (endTimestamp != null && endTimestamp != 0) {
                    endDateTime = new Timestamp(endTimestamp * 1000L); // 将秒转换为毫秒
                }

                if (startDateTime != null) {
                    queryWrapper.ge("created_at", startDateTime);
                }

                if (endDateTime != null) {
                    queryWrapper.le("created_at", endDateTime);
                }
                break;
            default:
                // 不处理未知的时间范围
                break;
        }
    }
    @Override
    public PageResponse<Orders> listOrdersByUsername(String username, int pageNo, int pageSize) {

            Users user = getUserByUsername(username);
            IPage<Orders> page = new Page<>(pageNo, pageSize);
            IPage<Orders> resultPage = ordersMapper.selectPage(page, new QueryWrapper<Orders>().eq("user_id", user.getUserId()));
            // 转换为通用返回对象
            PageResponse<Orders> response = new PageResponse<>();
            response.setOrderList(resultPage.getRecords());
            response.setTotal(resultPage.getTotal());
            response.setPageNo(resultPage.getCurrent());
            response.setPageSize(resultPage.getSize());

            return response;
    }

    @Override
    public Orders getOrderById(String orderId, String openId) {

        Orders orders = ordersMapper.selectByOrderId(orderId);
        if (orders == null) {
            throw new BusinessException(ExceptionEnum.ORDER_NOT_FOUND);
        }
            if (orders.getCreatedAt() != null) {
                try {
                    ZoneId zone = ZoneId.systemDefault();
                    ZonedDateTime zdt = orders.getCreatedAt().atZone(zone);
                    orders.setCreateStamp(zdt.toEpochSecond());
                } catch (DateTimeException e) {
                    log.error("时间转换异常，订单ID："+orders.getOrderId()+"错误："+ e.getMessage());
                    orders.setCreateStamp(0L); // 设置默认值
                }
            } else {
                log.warn("订单创建时间为空，ID：{}"+ orders.getOrderId());
                orders.setCreateStamp(0L);
            }

        Users byUserId = usersService.findByOpenId(openId);
        if (byUserId == null) {
            throw new BusinessException(ExceptionEnum.USER_NOT_FOUND);
        }
        // 查询地址信息
            QueryWrapper<ShippingInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orders.getOrderId());
            ShippingInfo shippingInfo = shippingInfoMapper.selectOne(queryWrapper);
            Addresses addresses = addressesMapper.selectById(shippingInfo.getAddressId());
            orders.setReceiver(addresses);

        // 查询产品信息
        List<Product> products = ordersMapper.selectProductsByOrderId(orderId);
        BigDecimal totalMoney = new BigDecimal(0);
        
        // 首先计算product_id为14、15、16、17的产品总数量
        int specialGroupTotalQuantity = 0;
        List<Integer> specialGroupProductIds = Arrays.asList(14, 15, 16, 17);
        
        for (Product product : products) {
            if (specialGroupProductIds.contains(product.getProductId())) {
                specialGroupTotalQuantity += product.getQuantity();
            }
        }
        
        // 决定特殊组产品是否使用批量价格
        boolean useBulkPriceForSpecialGroup = specialGroupTotalQuantity >= 2;
        
        // 计算每个产品的价格
        for (Product product : products) {
            Integer productId = product.getProductId();
            Integer quantity = product.getQuantity();
            BigDecimal productTotalPrice;
            
            if (productId == 13) {
                // 规则1: product_id为13的产品
                if (quantity >= product.getMinQuantity()) {
                    productTotalPrice = product.getBulkPrice().multiply(new BigDecimal(quantity));
                } else {
                    productTotalPrice = product.getSinglePrice().multiply(new BigDecimal(quantity));
                }
            } else if (specialGroupProductIds.contains(productId)) {
                // 规则2: product_id为14、15、16、17的产品
                if (useBulkPriceForSpecialGroup) {
                    productTotalPrice = product.getBulkPrice().multiply(new BigDecimal(quantity));
                } else {
                    productTotalPrice = product.getSinglePrice().multiply(new BigDecimal(quantity));
                }
            } else if (productId == 18) {
                // 规则3: product_id为18的产品，直接使用single_price
                productTotalPrice = product.getSinglePrice().multiply(new BigDecimal(quantity));
            } else {
                // 其他产品，使用默认逻辑
                if (quantity >= product.getMinQuantity()) {
                    productTotalPrice = product.getBulkPrice().multiply(new BigDecimal(quantity));
                } else {
                    productTotalPrice = product.getSinglePrice().multiply(new BigDecimal(quantity));
                }
            }
            
            // 设置产品总价并累加到订单总价
            product.setTotalMoney(productTotalPrice);
            totalMoney = totalMoney.add(productTotalPrice);
        }
        orders.setProducts(products);

        // 查询审批流信息
//            if(byUserId.getRole() == 0 || byUserId.getRole() == 1 ||  byUserId.getRole() == 2){
//                ApprovalRecord approvalRecord = getApprovalRecordByOrderId(orderId, byUserId);
//                orders.setApprovalRecord(approvalRecord);
//            }
        orders.setApprovalRecord(null);
            String status = orders.getStatus();
            if (status.equals("已支付") && (byUserId.getRole() == 0 || byUserId.getRole() == 1 || byUserId.getRole() == 2)) {
                orders.setIsSend(true);
            } else {
                orders.setIsSend(false);
            }


        return orders;
    }

    private Users getUserByUsername(String username) {
        return usersMapper.selectOne(new QueryWrapper<Users>().eq("username", username));
    }

    @Override
    public ApprovalRecord getApprovalRecordByOrderId(String orderId, Users users) {

        ApprovalRecord record = new ApprovalRecord();
        //董事长||开发者
        // 查询审批流信息
        QueryWrapper<ApprovalRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
//                .eq("users_id", orders.getUserId());

        // 执行查询，返回一个 ApprovalRecord 列表
        List<ApprovalRecord> approvalRecords = approvalRecordService.list(queryWrapper);
        Integer role = users.getRole();
        if (role == 1 || role == 0) {
            //董事长||开发者
            for (ApprovalRecord approvalRecord : approvalRecords) {
                int nodeId = approvalRecord.getNodeId();
                LocalDateTime approveTime = approvalRecord.getApproveTime();
                long createStamp = approveTime.toEpochSecond(ZoneOffset.UTC); // 使用 UTC 时区
                approvalRecord.setApproveStamp(createStamp);
                String approveStatus = approvalRecord.getApproveStatus();

                if ("审批中".equals(approveStatus)) {
                    record.setIsShow(true);
                }
            }
        } else if (role == 2) {
            for (ApprovalRecord approvalRecord : approvalRecords) {
                int nodeId = approvalRecord.getNodeId();
                LocalDateTime approveTime = approvalRecord.getApproveTime();
                long createStamp = approveTime.toEpochSecond(ZoneOffset.UTC); // 使用 UTC 时区
                approvalRecord.setApproveStamp(createStamp);
                String approveStatus = approvalRecord.getApproveStatus();
                if (Objects.equals(approveStatus, "审批中") && nodeId == 1) {
                    record.setIsShow(true);
                }
            }
        } else if (role == 3) {
            //普通角色不展示审批
             }

            record.setApprovalRecordList(approvalRecords);
            return record;
    }

    @Override
    public int selectByStatus() {
        List<Orders> ordersList = ordersMapper.selectList(new QueryWrapper<Orders>().eq("status", "待支付"));
        ordersList.forEach(orders -> {
            String orderId = orders.getOrderId();
            try {
                if(orders.getStatus().equals("待支付")){
                    shippingInfoMapper.delete(new QueryWrapper<ShippingInfo>().eq("order_id", orderId));
                    orderDetailsMapper.delete(new QueryWrapper<OrderDetails>().eq("order_id", orderId));
                }

            }catch (Exception e){
                log.error("异常，订单ID："+orders.getOrderId()+"错误："+ e.getMessage());
            }
            ordersMapper.delete(new QueryWrapper<Orders>().eq("order_id", orderId).eq("status","待支付"));
        });
        return 0;
    }

    @Override
    public boolean updateOrderAddressId(String orderId, Integer addressId) {
        log.info("【订单地址更新】开始更新订单地址，订单ID：{}, 地址ID：{}", orderId, addressId);

        try {
            // 1. 验证参数
            if (orderId == null || orderId.trim().isEmpty()) {
                log.error("【订单地址更新】订单ID不能为空");
                throw new BusinessException(ExceptionEnum.PARAM_ERROR, "订单ID不能为空");
            }
            if (addressId == null || addressId <= 0) {
                log.error("【订单地址更新】地址ID不能为空或无效");
                throw new BusinessException(ExceptionEnum.PARAM_ERROR, "地址ID不能为空或无效");
            }

            // 2. 检查订单是否存在
            Orders order = ordersMapper.selectByOrderId(orderId);
            if (order == null) {
                log.error("【订单地址更新】订单不存在，订单ID：{}", orderId);
                throw new BusinessException(ExceptionEnum.ORDER_NOT_FOUND);
            }

            // 3. 检查地址是否存在
            Addresses address = addressesMapper.selectById(addressId);
            if (address == null) {
                log.error("【订单地址更新】地址不存在，地址ID：{}", addressId);
                throw new BusinessException(ExceptionEnum.ADDRESS_NOT_FOUND);
            }

            // 4. 查询shippingInfo记录
            QueryWrapper<ShippingInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderId);
            ShippingInfo shippingInfo = shippingInfoMapper.selectOne(queryWrapper);

            if (shippingInfo == null) {
                log.error("【订单地址更新】未找到订单对应的物流信息，订单ID：{}", orderId);
                throw new BusinessException(ExceptionEnum.SHIPPING_INFO_NOT_FOUND);
            }

            // 5. 更新shippingInfo中的addressId
            ShippingInfo updateShippingInfo = new ShippingInfo();
            updateShippingInfo.setAddressId(addressId);
            updateShippingInfo.setUpdatedAt(LocalDateTime.now());

            UpdateWrapper<ShippingInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("order_id", orderId);

            int rowsAffected = shippingInfoMapper.update(updateShippingInfo, updateWrapper);

            if (rowsAffected > 0) {
                log.info("【订单地址更新】更新成功，订单ID：{}, 地址ID：{}", orderId, addressId);
                return true;
            } else {
                log.error("【订单地址更新】更新失败，未找到匹配的记录，订单ID：{}", orderId);
                return false;
            }
        } catch (BusinessException e) {
            log.warn("【业务异常】订单地址更新失败，错误码：{}", e.getCode());
            throw e;
        } catch (Exception e) {
            log.error("【系统异常】订单地址更新错误，异常类型：{}，错误信息：{}", e.getClass().getSimpleName(), e.getMessage());
            throw new BusinessException(ExceptionEnum.UNKNOWN_ERROR, e.getMessage());
        }
    }

    @Override
    public List<Addresses> getAddressByOrderId(String orderId) {
        log.info("【订单地址查询】开始根据订单ID查询用户的所有地址信息，订单ID：{}", orderId);

        try {
            // 1. 验证参数
            if (orderId == null || orderId.trim().isEmpty()) {
                log.error("【订单地址查询】订单ID不能为空");
                throw new BusinessException(ExceptionEnum.PARAM_ERROR, "订单ID不能为空");
            }

            // 2. 检查订单是否存在并获取用户ID
            Orders order = ordersMapper.selectByOrderId(orderId);
            if (order == null) {
                log.error("【订单地址查询】订单不存在，订单ID：{}", orderId);
                throw new BusinessException(ExceptionEnum.ORDER_NOT_FOUND);
            }

            Long userId = order.getUserId();
            if (userId == null) {
                log.error("【订单地址查询】订单中未找到用户ID，订单ID：{}", orderId);
                throw new BusinessException(ExceptionEnum.USER_NOT_FOUND, "订单中未找到用户信息");
            }

            // 3. 根据用户ID查询该用户的所有地址信息，并按创建时间降序排序
            QueryWrapper<Addresses> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.orderByDesc("created_at"); // 按创建时间降序排序，新创建的地址排在前面

            List<Addresses> addressesList = addressesMapper.selectList(queryWrapper);

            if (addressesList == null || addressesList.isEmpty()) {
                log.warn("【订单地址查询】未找到用户的地址信息，用户ID：{}", userId);
                throw new BusinessException(ExceptionEnum.ADDRESS_NOT_FOUND, "未找到该用户的地址信息");
            }

            log.info("【订单地址查询】查询成功，订单ID：{}，共查询到{}条地址信息", orderId, addressesList.size());
            return addressesList;
        } catch (BusinessException e) {
            log.warn("【业务异常】订单地址查询失败，错误码：{}", e.getCode());
            throw e;
        } catch (Exception e) {
            log.error("【系统异常】订单地址查询错误，异常类型：{}，错误信息：{}", e.getClass().getSimpleName(), e.getMessage());
            throw new BusinessException(ExceptionEnum.UNKNOWN_ERROR, e.getMessage());
        }
    }

    @Override
    public UserOrderStatisticsResponse getUserOrderStatistics(String timeDimension, Long startTime, Long endTime) {
        log.info("【用户订单统计】开始统计，时间维度：{}", timeDimension);

        try {
            // 1. 确定时间范围
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime startTimeLocal = null;
            LocalDateTime endTimeLocal = now;

            // 根据时间维度设置查询条件
            QueryWrapper<Orders> timeQueryWrapper = new QueryWrapper<>();
            switch (timeDimension) {
                case "all":
                    // 优化：对于all维度，限制只查询最近1年的数据，避免查询过多历史数据
                    startTimeLocal = now.minusYears(1);
                    timeQueryWrapper.ge("created_at", startTimeLocal);
                    break;
                case "1d":
                    startTimeLocal = now.minusDays(1);
                    timeQueryWrapper.ge("created_at", startTimeLocal);
                    break;
                case "7d":
                    startTimeLocal = now.minusDays(7);
                    timeQueryWrapper.ge("created_at", startTimeLocal);
                    break;
                case "15d":
                    startTimeLocal = now.minusDays(15);
                    timeQueryWrapper.ge("created_at", startTimeLocal);
                    break;
                case "30d":
                    startTimeLocal = now.minusDays(30);
                    timeQueryWrapper.ge("created_at", startTimeLocal);
                    break;
                case "custom":
                    if (startTime != null && endTime != null) {
                        startTimeLocal = LocalDateTime.ofEpochSecond(startTime, 0, ZoneOffset.UTC);
                        endTimeLocal = LocalDateTime.ofEpochSecond(endTime, 0, ZoneOffset.UTC);
                        timeQueryWrapper.ge("created_at", startTimeLocal).le("created_at", endTimeLocal);
                    } else {
                        throw new BusinessException(ExceptionEnum.DATE_ERROR, "自定义时间范围参数缺失");
                    }
                    break;
                default:
                    throw new BusinessException(ExceptionEnum.PARAM_ERROR, "无效的时间维度");
            }

            // 2. 查询时间段内的有效订单（已支付和已发货状态）用于金额和产品统计，同时用于订单数统计
            QueryWrapper<Orders> validOrdersQueryWrapper = new QueryWrapper<>();
            // 应用时间范围值
            if (startTimeLocal != null) {
                validOrdersQueryWrapper.ge("created_at", startTimeLocal);
            }
            if (endTimeLocal != null) {
                validOrdersQueryWrapper.le("created_at", endTimeLocal);
            }
            // 添加状态条件
            validOrdersQueryWrapper.in("status", Arrays.asList("已支付", "已发货"));
            // 优化：使用selectMaps直接获取需要的字段，减少数据传输
            List<Map<String, Object>> periodValidOrderMaps = ordersMapper.selectMaps(validOrdersQueryWrapper.select("order_id", "user_id", "real_amount", "created_at"));
            Integer periodOrderCount = periodValidOrderMaps.size();

            // 3. 优化：使用聚合查询直接从数据库获取总金额，避免查询所有订单
            BigDecimal totalAmount = getTotalAmountFromDatabase();

            // 4. 优化：使用SQL聚合查询直接获取时间段内金额，避免在内存中处理大量数据
            BigDecimal periodAmount;
            if (periodValidOrderMaps.isEmpty()) {
                periodAmount = BigDecimal.ZERO;
            } else {
                QueryWrapper<Orders> periodAmountQuery = new QueryWrapper<>();
                if (startTimeLocal != null) {
                    periodAmountQuery.ge("created_at", startTimeLocal);
                }
                if (endTimeLocal != null) {
                    periodAmountQuery.le("created_at", endTimeLocal);
                }
                periodAmountQuery.in("status", Arrays.asList("已支付", "已发货"));
                Map<String, Object> result = ordersMapper.selectMaps(periodAmountQuery.select("IFNULL(SUM(real_amount), 0) as periodAmount")).get(0);
                periodAmount = (BigDecimal) result.get("periodAmount");
            }

            // 6. 统计时间段内的产品数量
            Map<Integer, Integer> productQuantityStats = new HashMap<>();
            int totalProductQuantity = 0;

            // 收集所有需要查询的订单ID
            Set<String> validOrderIds = periodValidOrderMaps.stream()
                    .map(map -> (String) map.get("order_id"))
                    .collect(java.util.stream.Collectors.toSet());

            log.info("【产品数量统计】有效订单数量：{}, 有效订单ID数量：{}", periodValidOrderMaps.size(), validOrderIds.size());

            // 优化：使用SQL聚合查询直接获取产品数量统计，避免大量数据传输和循环处理
            if (!validOrderIds.isEmpty()) {
                productQuantityStats = getProductQuantityStatsFromDatabase(validOrderIds);
                totalProductQuantity = productQuantityStats.values().stream().mapToInt(Integer::intValue).sum();
                log.info("【产品数量统计】最终产品18数量：{}", productQuantityStats.getOrDefault(18, 0));
            }

            // 7. 生成用户订单统计数据，包含userId、username、totalOrders和totalAmount，不包含productStats
            List<UserOrderStatisticsResponse.UserOrderStat> userOrderStats = new ArrayList<>();
            
            // 从periodValidOrderMaps中按用户ID分组，处理可能的Integer类型user_id
            Map<Long, List<Map<String, Object>>> userOrderMap = periodValidOrderMaps.stream()
                    .collect(java.util.stream.Collectors.groupingBy(map -> {
                        Object userIdObj = map.get("user_id");
                        if (userIdObj instanceof Integer) {
                            return ((Integer) userIdObj).longValue();
                        } else if (userIdObj instanceof Long) {
                            return (Long) userIdObj;
                        } else {
                            log.warn("未知的用户ID类型: {}", userIdObj != null ? userIdObj.getClass().getName() : "null");
                            return 0L;
                        }
                    }));
            
            // 优化：批量查询所有用户的地址信息，避免N+1查询问题
            Set<Long> userIds = userOrderMap.keySet();
            Map<Long, Addresses> userAddressMap = new HashMap<>();
            if (!userIds.isEmpty()) {
                List<Addresses> addressesList = addressesMapper.selectList(
                        new QueryWrapper<Addresses>().in("user_id", userIds).last("GROUP BY user_id"));
                for (Addresses address : addressesList) {
                    userAddressMap.put(address.getUserId(), address);
                }
            }
            
            // 遍历每个用户的订单
            for (Map.Entry<Long, List<Map<String, Object>>> entry : userOrderMap.entrySet()) {
                Long userId = entry.getKey();
                List<Map<String, Object>> userOrders = entry.getValue();
                
                // 创建用户统计对象
                UserOrderStatisticsResponse.UserOrderStat userStat = new UserOrderStatisticsResponse.UserOrderStat();
                userStat.setUserId(userId);
                userStat.setTotalOrders(userOrders.size());
                
                // 计算用户总金额
                BigDecimal userTotalAmount = userOrders.stream()
                        .map(map -> (BigDecimal) map.get("real_amount"))
                        .filter(Objects::nonNull)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                userStat.setTotalAmount(userTotalAmount);
                
                // 从预加载的地址Map中获取用户地址信息
                Addresses address = userAddressMap.get(userId);
                if (address != null) {
                    String username = String.format("%s-%s-%s-%s",
                            address.getProvince(),
                            address.getCity(),
                            address.getName(),
                            address.getHouseNumber());
                    userStat.setUsername(username);
                } else {
                    userStat.setUsername("未知用户");
                }
                
                userOrderStats.add(userStat);
            }
            
            // 8. 按总金额降序排序
            userOrderStats.sort((u1, u2) -> {
                // 处理可能为null的情况
                BigDecimal amount1 = u1.getTotalAmount() != null ? u1.getTotalAmount() : BigDecimal.ZERO;
                BigDecimal amount2 = u2.getTotalAmount() != null ? u2.getTotalAmount() : BigDecimal.ZERO;
                return amount2.compareTo(amount1);
            });
            
            // 只取totalAmount倒序前15名最高的金额
            if (userOrderStats.size() > 15) {
                userOrderStats = userOrderStats.subList(0, 15);
            }

            // 9. 统计真正下过单的用户数
            // 直接使用userOrderMap的大小，因为它只包含有订单的用户ID
            Integer totalUserCount = userOrderMap.size();

            // 10. 生成象限图数据
            List<UserOrderStatisticsResponse.TimeIntervalStat> timeIntervalStats = new ArrayList<>();
            if (!periodValidOrderMaps.isEmpty()) {
                // 根据时间维度确定区间类型
                switch (timeDimension) {
                    case "1d":
                        // 1天内按小时统计
                        timeIntervalStats = generateHourlyStats(periodValidOrderMaps, startTimeLocal, endTimeLocal);
                        break;
                    case "7d":
                    case "15d":
                    case "30d":
                    case "custom":
                        // 7/15/30天和自定义时间范围按天统计
                        timeIntervalStats = generateDailyStats(periodValidOrderMaps, startTimeLocal, endTimeLocal);
                        break;
                    case "all":
                        // 全部按月份统计
                        timeIntervalStats = generateMonthlyStats(periodValidOrderMaps);
                        break;
                }
            }

            // 10. 构建响应对象
            UserOrderStatisticsResponse response = new UserOrderStatisticsResponse();
            response.setTotalAmount(totalAmount);
            response.setPeriodAmount(periodAmount);
            response.setPeriodOrderCount(periodOrderCount);
            response.setProductQuantityStats(productQuantityStats);
            response.setTotalProductQuantity(totalProductQuantity);
            response.setTotalUserCount(totalUserCount);
            response.setUserOrderStats(userOrderStats);
            response.setTimeIntervalStats(timeIntervalStats);

            log.info("【用户订单统计】统计完成，总用户数：{}, 时间段内订单数：{}, 总产品数量：{}, 时间段内金额：{}, 象限图数据区间数：{}",
                     totalUserCount, periodOrderCount, totalProductQuantity, periodAmount, timeIntervalStats.size());
            return response;

        } catch (BusinessException e) {
            log.warn("【业务异常】订单统计失败，错误码：{}", e.getCode());
            throw e;
        } catch (Exception e) {
            log.error("【系统异常】订单统计错误，异常类型：{}，错误信息：{}", e.getClass().getSimpleName(), e.getMessage());
            throw new BusinessException(ExceptionEnum.UNKNOWN_ERROR, e.getMessage());
        }
    }

    /**
     * 生成按小时统计的象限图数据
     */
    private List<UserOrderStatisticsResponse.TimeIntervalStat> generateHourlyStats(List<Map<String, Object>> validOrderMaps,
                                                                                 LocalDateTime startTime,
                                                                                 LocalDateTime endTime) {
        List<UserOrderStatisticsResponse.TimeIntervalStat> stats = new ArrayList<>();

        // 按小时分组订单
        Map<String, List<Map<String, Object>>> hourlyOrdersMap = validOrderMaps.stream()
                .collect(java.util.stream.Collectors.groupingBy(map -> {
                    Object createdAtObj = map.get("created_at");
                    LocalDateTime createdAt;
                    if (createdAtObj instanceof Timestamp) {
                        createdAt = ((Timestamp) createdAtObj).toLocalDateTime();
                    } else if (createdAtObj instanceof LocalDateTime) {
                        createdAt = (LocalDateTime) createdAtObj;
                    } else {
                        log.warn("未知的时间类型: {}", createdAtObj != null ? createdAtObj.getClass().getName() : "null");
                        return "未知时间";
                    }
                    return createdAt.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:00"));
                }));

        // 优化：预先获取所有需要的订单详情，避免多次查询
        Set<String> allOrderIds = validOrderMaps.stream()
                .map(map -> (String) map.get("order_id"))
                .collect(java.util.stream.Collectors.toSet());
        Map<String, List<OrderDetails>> orderDetailsMap = new HashMap<>();
        if (!allOrderIds.isEmpty()) {
            QueryWrapper<OrderDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("order_id", allOrderIds);
            List<OrderDetails> allDetails = orderDetailsMapper.selectList(queryWrapper);
            // 按订单ID分组
            orderDetailsMap = allDetails.stream()
                    .collect(java.util.stream.Collectors.groupingBy(OrderDetails::getOrderId));
        }

        // 生成每小时的统计数据
        LocalDateTime currentHour = startTime.withMinute(0).withSecond(0).withNano(0);
        while (currentHour.isBefore(endTime) || currentHour.isEqual(endTime)) {
            String hourLabel = currentHour.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:00"));
            List<Map<String, Object>> hourOrders = hourlyOrdersMap.getOrDefault(hourLabel, new ArrayList<>());

            // 计算该小时内的金额
            BigDecimal hourAmount = hourOrders.stream()
                    .map(map -> (BigDecimal) map.get("real_amount"))
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            // 统计该小时内的产品数量
            Map<Integer, Integer> productQuantityMap = new HashMap<>();
            int totalProductQuantity = 0;

            // 收集所有需要查询的订单ID
            Set<String> orderIds = hourOrders.stream()
                    .map(map -> (String) map.get("order_id"))
                    .collect(java.util.stream.Collectors.toSet());

            // 使用预先获取的订单详情，避免重复查询
            for (String orderId : orderIds) {
                List<OrderDetails> details = orderDetailsMap.getOrDefault(orderId, Collections.emptyList());
                for (OrderDetails detail : details) {
                    Integer productId = detail.getProductId();
                    Integer quantity = detail.getQuantity();
                    productQuantityMap.put(productId, productQuantityMap.getOrDefault(productId, 0) + quantity);
                    totalProductQuantity += quantity;
                }
            }

            // 添加小时统计
            stats.add(new UserOrderStatisticsResponse.TimeIntervalStat(
                    hourLabel.substring(11), // 只保留HH:00格式
                    hourAmount,
                    hourOrders.size(),
                    productQuantityMap,
                    totalProductQuantity
            ));

            // 移动到下一小时
            currentHour = currentHour.plusHours(1);
        }

        return stats;
    }

    /**
     * 生成按天统计的象限图数据
     */
    private List<UserOrderStatisticsResponse.TimeIntervalStat> generateDailyStats(List<Map<String, Object>> validOrderMaps,
                                                                                LocalDateTime startTime,
                                                                                LocalDateTime endTime) {
        List<UserOrderStatisticsResponse.TimeIntervalStat> stats = new ArrayList<>();

        // 按天分组订单
        Map<String, List<Map<String, Object>>> dailyOrdersMap = validOrderMaps.stream()
                .collect(java.util.stream.Collectors.groupingBy(map -> {
                    Object createdAtObj = map.get("created_at");
                    LocalDateTime createdAt;
                    if (createdAtObj instanceof Timestamp) {
                        createdAt = ((Timestamp) createdAtObj).toLocalDateTime();
                    } else if (createdAtObj instanceof LocalDateTime) {
                        createdAt = (LocalDateTime) createdAtObj;
                    } else {
                        log.warn("未知的时间类型: {}", createdAtObj != null ? createdAtObj.getClass().getName() : "null");
                        return "未知时间";
                    }
                    return createdAt.format(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE);
                }));

        // 优化：预先获取所有需要的订单详情，避免多次查询
        Set<String> allOrderIds = validOrderMaps.stream()
                .map(map -> (String) map.get("order_id"))
                .collect(java.util.stream.Collectors.toSet());
        Map<String, List<OrderDetails>> orderDetailsMap = new HashMap<>();
        if (!allOrderIds.isEmpty()) {
            QueryWrapper<OrderDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("order_id", allOrderIds);
            List<OrderDetails> allDetails = orderDetailsMapper.selectList(queryWrapper);
            // 按订单ID分组
            orderDetailsMap = allDetails.stream()
                    .collect(java.util.stream.Collectors.groupingBy(OrderDetails::getOrderId));
        }

        // 生成每天的统计数据
        LocalDateTime currentDay = startTime.withHour(0).withMinute(0).withSecond(0).withNano(0);
        while (currentDay.isBefore(endTime.plusDays(1)) && !currentDay.isAfter(endTime.withHour(23).withMinute(59).withSecond(59))) {
            String dayLabel = currentDay.format(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE);
            List<Map<String, Object>> dayOrders = dailyOrdersMap.getOrDefault(dayLabel, new ArrayList<>());

            // 计算该天内的金额
            BigDecimal dayAmount = dayOrders.stream()
                    .map(map -> (BigDecimal) map.get("real_amount"))
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            // 统计该天内的产品数量
            Map<Integer, Integer> productQuantityMap = new HashMap<>();
            int totalProductQuantity = 0;

            // 收集所有需要查询的订单ID
            Set<String> orderIds = dayOrders.stream()
                    .map(map -> (String) map.get("order_id"))
                    .collect(java.util.stream.Collectors.toSet());

            // 使用预先获取的订单详情，避免重复查询
            for (String orderId : orderIds) {
                List<OrderDetails> details = orderDetailsMap.getOrDefault(orderId, Collections.emptyList());
                for (OrderDetails detail : details) {
                    Integer productId = detail.getProductId();
                    Integer quantity = detail.getQuantity();
                    productQuantityMap.put(productId, productQuantityMap.getOrDefault(productId, 0) + quantity);
                    totalProductQuantity += quantity;
                }
            }

            // 添加天统计
            stats.add(new UserOrderStatisticsResponse.TimeIntervalStat(
                    dayLabel.substring(5), // 只保留MM-dd格式
                    dayAmount,
                    dayOrders.size(),
                    productQuantityMap,
                    totalProductQuantity
            ));

            // 移动到下一天
            currentDay = currentDay.plusDays(1);
        }

        return stats;
    }

    /**
     * 生成按月份统计的象限图数据
     */
    private List<UserOrderStatisticsResponse.TimeIntervalStat> generateMonthlyStats(List<Map<String, Object>> validOrderMaps) {
        List<UserOrderStatisticsResponse.TimeIntervalStat> stats = new ArrayList<>();

        // 按月份分组订单
        Map<String, List<Map<String, Object>>> monthlyOrdersMap = validOrderMaps.stream()
                .collect(java.util.stream.Collectors.groupingBy(map -> {
                    Object createdAtObj = map.get("created_at");
                    LocalDateTime createdAt;
                    if (createdAtObj instanceof Timestamp) {
                        createdAt = ((Timestamp) createdAtObj).toLocalDateTime();
                    } else if (createdAtObj instanceof LocalDateTime) {
                        createdAt = (LocalDateTime) createdAtObj;
                    } else {
                        log.warn("未知的时间类型: {}", createdAtObj != null ? createdAtObj.getClass().getName() : "null");
                        return "未知时间";
                    }
                    return createdAt.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM"));
                }));

        // 优化：预先获取所有需要的订单详情，避免多次查询
        Set<String> allOrderIds = validOrderMaps.stream()
                .map(map -> (String) map.get("order_id"))
                .collect(java.util.stream.Collectors.toSet());
        Map<String, List<OrderDetails>> orderDetailsMap = new HashMap<>();
        if (!allOrderIds.isEmpty()) {
            QueryWrapper<OrderDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("order_id", allOrderIds);
            List<OrderDetails> allDetails = orderDetailsMapper.selectList(queryWrapper);
            // 按订单ID分组
            orderDetailsMap = allDetails.stream()
                    .collect(java.util.stream.Collectors.groupingBy(OrderDetails::getOrderId));
        }

        // 获取所有月份并排序
        List<String> sortedMonths = new ArrayList<>(monthlyOrdersMap.keySet());
        sortedMonths.sort(String::compareTo);

        // 生成每月的统计数据
        for (String monthLabel : sortedMonths) {
            List<Map<String, Object>> monthOrders = monthlyOrdersMap.get(monthLabel);

            // 计算该月内的金额
            BigDecimal monthAmount = monthOrders.stream()
                    .map(map -> (BigDecimal) map.get("real_amount"))
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            // 统计该月内的产品数量
            Map<Integer, Integer> productQuantityMap = new HashMap<>();
            int totalProductQuantity = 0;

            // 收集所有需要查询的订单ID
            Set<String> orderIds = monthOrders.stream()
                    .map(map -> (String) map.get("order_id"))
                    .collect(java.util.stream.Collectors.toSet());

            // 使用预先获取的订单详情，避免重复查询
            for (String orderId : orderIds) {
                List<OrderDetails> details = orderDetailsMap.getOrDefault(orderId, Collections.emptyList());
                for (OrderDetails detail : details) {
                    Integer productId = detail.getProductId();
                    Integer quantity = detail.getQuantity();
                    productQuantityMap.put(productId, productQuantityMap.getOrDefault(productId, 0) + quantity);
                    totalProductQuantity += quantity;
                }
            }

            // 添加月统计
            stats.add(new UserOrderStatisticsResponse.TimeIntervalStat(
                    monthLabel,
                    monthAmount,
                    monthOrders.size(),
                    productQuantityMap,
                    totalProductQuantity
            ));
        }

        return stats;
    }

        // 新增加的辅助方法
        /**
         * 从数据库获取总金额统计
         */
        private BigDecimal getTotalAmountFromDatabase() {
            // 使用SQL聚合查询直接获取总金额
            Map<String, Object> result = ordersMapper.selectMaps(new QueryWrapper<Orders>()
                    .in("status", Arrays.asList("已支付", "已发货"))
                    .select("IFNULL(SUM(real_amount), 0) as totalAmount")).get(0);
            return (BigDecimal) result.get("totalAmount");
        }

        /**
         * 从数据库获取产品数量统计
         */
        private Map<Integer, Integer> getProductQuantityStatsFromDatabase(Set<String> orderIds) {
            // 使用SQL聚合查询直接获取产品数量统计
            List<Map<String, Object>> results = orderDetailsMapper.selectMaps(new QueryWrapper<OrderDetails>()
                    .in("order_id", orderIds)
                    .groupBy("product_id")
                    .select("product_id, SUM(quantity) as totalQuantity"));

            Map<Integer, Integer> stats = new HashMap<>();
            for (Map<String, Object> result : results) {
                stats.put((Integer) result.get("product_id"), ((BigDecimal) result.get("totalQuantity")).intValue());
            }
            return stats;
        }

        // 删除了不再使用的用户订单统计相关方法

        /**
         * 从数据库获取总用户数
         */
        private Integer getTotalUserCountFromDatabase() {
            // 使用缓存逻辑的简化版本，实际可以考虑添加更复杂的缓存策略
            return Math.toIntExact(usersMapper.selectCount(new QueryWrapper<Users>().eq("status", "正常")));
        }
}




